const { BaseCommand } = require("./base");
const path = require("node:path");
const { get_fst_file, get_full_path } = require("../utils/file_tool");
const { info } = require("../utils/log_tool");
const { progress } = require("../utils/display_tool");
const { eval_code } = require("./share_data");

class ZipFolderCommand extends BaseCommand {
    async execute() {
        const AdmZip = require("adm-zip");
        const data = this.selfData;
        const folder = get_fst_file(data.src);
        const isAccept = data.filter
            ? eval_code(data.filter)
            : (filename) => {
                  // 排除以 . 开头的文件、目录
                  if (
                      filename
                          .split(path.sep)
                          .some((part) => part.startsWith("."))
                  ) {
                      return false;
                  }
                  return true;
              };
        // creating archives
        var zip = new AdmZip();
        let i = 0;
        zip.addLocalFolder(folder, "", (filename) => {
            if (!isAccept(filename)) {
                return false;
            }
            data.verbose &&
                progress(i++, 0, {
                    desc: `${filename}`,
                    depth: 0,
                    align: true,
                });
            return true;
        });
        // or write everything to disk
        if (data.dst) {
            const dst = get_full_path(data.dst);
            await new Promise((resolve) => {
                zip.writeZip(dst, (err) => {
                    if (err) {
                        throw err;
                    }
                    resolve();
                });
            });
        } else {
            const buffer = zip.toBuffer();
            return buffer;
        }
    }
}

module.exports = {
    ZipFolderCommand,
};
